package com.melodyframe.stage.supports.freemarker.directive;

import java.io.IOException;
import java.io.Writer;
import java.util.Map;

import com.melodyframe.common.context.ContextLocal;
import com.melodyframe.common.context.ContextProxy;
import com.melodyframe.stage.core.Stage;
import com.melodyframe.stage.core.renderer.View;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

public class StageDirective implements TemplateDirectiveModel {

	private Stage	stage;

	public StageDirective(Stage stage) {
		this.stage = stage;
	}

	@Override
	public void execute(Environment env,
			@SuppressWarnings("rawtypes") Map params, TemplateModel[] models,
			TemplateDirectiveBody body) throws TemplateException, IOException {
		if (null != this.stage && params.containsKey("path")) {
			View view = this.stage.perform(params.get("path").toString(),
					new ContextProxy(ContextLocal.getContext()));
			Writer out = env.getOut();
			out.write(view.getResponseText());
			out.flush();
		}
	}

}
